package com.zj.core.services

import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.zj.core.activity.LoginActivity
import com.zj.core.base.BaseApplication

/**
 * 日期：2019年4月4日
 * 公司：北京子杰宝贝科技有限公司
 * 地址：北京市朝阳区朝阳农场
 * 开发者：达选文
 * 功能：开机自启
 * <p>
 */
class LaunchReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent){
        try {
            if (appOnForeground()){
                Log.d("LaunchReceiver","当前App处于前台")
            } else {
                if (intent.action == "android.intent.action.BOOT_COMPLETED") {
                    val i = Intent(context, LoginActivity::class.java)
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    context.startActivity(i)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun appOnForeground(): Boolean {
        val activityManager = BaseApplication.context?.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val packageName = BaseApplication.context!!.packageName
        val appProcesses = activityManager.runningAppProcesses ?: return false
        for (appProcess in appProcesses) {
            if (appProcess.processName == packageName && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true
            }
        }
        return false
    }
}